class Path < ActiveRecord::Base
    belongs_to :user
    has_many :steps
    has_many :links, :through => :steps
    
    validates_presence_of :user_id, :title
    
    CONST_START_URI = "http://www.makeapath.com/paths/"
    CONST_START_TITLE = "Beginning of Path"
    CONST_RELATION = "comes before"
    CONST_NIL_URI = "http://www.makeapath.com/nil/"
    CONST_DEFAULT_PATH_TITLE = 'Click to Edit Title...'
    
    ##############################
    # used to update the step order in an array - updated
    def update_step_order(id_array) 
        
        #check to see if any steps have been deleted and remove from database.
        #debugger
#        puts id_array.each {|foo| print foo, ", "}
        if !id_array.nil? && id_array.length < self.steps.length
            self.steps.each do |j|
                if id_array.index(j.id.to_s).nil?
                    self.steps.delete(Step.find(j.id))
                end
            end
        end
        
        # This code should only execute on the last step found in the path has been deleted.
        if id_array.nil?
            self.steps.clear
        end
        
        0.upto(id_array.length - 1) do |i|
            s = Step.find(id_array[i])
            if s.sequence != i
                s.sequence = i
                s.save!
            end
        end
    end
    
    ####################################
    # Sets the status to whatever it was not set to - updated
    def toggle_published_status
        if self.published == true
            self.published = false
        else
            self.published = true
        end
        self.save!
    end
    
    ###################################
    # Appends a step to a path
    def append_step(uri, title)
        
        steps = self.steps.find(:all, :order => "sequence")
        if steps.length > 0
            send_to_didily(steps.last.uri, steps.last.title, uri, title)
        end
                
        @step = Step.new
        @step.title = title
        @step.uri = uri
        @step.sequence = steps.length
        @step.save
        
        self.steps.push(@step)      
        self.save
        
    end
    
    ###################################
    # Appends a page to a path - updated
    def update_path_titles(title_hash)
        self.title = title_hash[:title]
        self.save!
        
        i = 0
        s = self.steps.find(:all, :order => "sequence")
        while !s[i].nil?
            s[i].title = title_hash['title_' + s[i].id.to_s]
            s[i].save!
            i += 1
        end
        return true
    end
    
    ###############################################
    # validation method called when model is saved
    def validate
        if !@link_errors.nil? and @link_errors.length > 0
            @link_errors.each do |error|
                errors.add('URL:', error)
            end
        end      
    end
    
    
    ###################################
    # Update didily with a new relationship as paths are appended.
    def send_to_didily(from_uri, from_title, to_uri, to_title)
        require 'net/http'
        require 'uri'
    
        relation = 'comes before'
        key = Account::AccountConfiguration.config(:makeapath_didily_api_key)
        uri = "http://scrumdidilyumptio.us/didilies"        
        res = Net::HTTP.post_form(URI.parse(uri), 
                                   {"key" => key,
                                    "didily[from_uri]" => from_uri,
                                    "didily[from_title]" => from_title,
                                    "didily[relation]" => relation,
                                    "didily[to_uri]" => to_uri,
                                    "didily[to_title]" => to_title
                                   })
    end
    
end
